package com.ship.dispatch.model.execl;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ship.dispatch.service.decisionAnalysis.SmShipRentService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Data
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class ShipRentImportListener extends AnalysisEventListener<ShipRentExcel> {
    /**
     * 默认每隔3000条存储数据库
     */
    private int batchCount = 3000;
    /**
     * 缓存的数据列表
     */
    private List<ShipRentExcel> list = new ArrayList<>();

    private SmShipRentService shipRentService;

    private String sheetName;

    public ShipRentImportListener(SmShipRentService shipRentService){
        this.shipRentService = shipRentService;
    }

    @Override
    public void invoke(ShipRentExcel data, AnalysisContext context) {
        sheetName =  context.readSheetHolder().getSheetName();
        if(null != data.getWeek()){
            list.add(data);
        }
        // 达到BATCH_COUNT，则调用importer方法入库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= batchCount) {
            // 调用importer方法
            shipRentService.importShipRent(list,sheetName);
            // 存储完成清理list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 调用importer方法
        shipRentService.importShipRent(list,sheetName);
        // 存储完成清理list
        list.clear();
    }
}
